import 'package:getx_demo/common/utils/utils.dart';
import 'package:getx_demo/common/values/values.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'index.dart';

class UserinfoPage extends GetView<UserinfoController> {
  const UserinfoPage({super.key});
  final String imageUrl = '';
  final bool isPhotoUrl = false;

  // 主视图
  Widget _buildView() {
    return Center(
      child: Column(
        children: [
          SizedBox(
            height: 160,
            child: _setupView(),
          ),
          _buildRowCell(title: '星级', text: '初出茅庐'),
          _buildRowCell(title: '姓名', text: controller.baseInfo?.nickName),
          _buildRowCell(title: '工号', text: controller.baseInfo?.jobId),
          _buildRowCell(
            title: '地区',
            text: controller.baseInfo?.regionName,
            onTap: _pickAction,
          ),
          _buildRowCell(
            title: '个人业绩',
            onTap: () {
              // Navigator.of(context).push(
              //   MaterialPageRoute(builder: (content) {
              //     return const PersonalAchievementPage();
              //   }),
              // );
            },
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<UserinfoController>(
      init: UserinfoController(),
      id: "userinfo",
      builder: (_) {
        return Scaffold(
          appBar: AppBar(title: const Text("个人信息")),
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }

  _setupView() {
    return Align(
      alignment: Alignment.topCenter,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
            width: 86.5,
            height: 86.5,
            left: 144.5,
            top: 42.5,
            child: _buildTopImageView(),
          ),
          Positioned(
            width: 21.5,
            height: 21.5,
            left: 211,
            top: 109,
            child: _buildChoosePhotoView(),
          ),
        ],
      ),
    );
  }

  Container _buildTopImageView() {
    // debugPrint('widget.myMessage.avatarUrl==${widget.myMessage.avatarUrl}');

    return Container(
      width: 86.5,
      height: 86.5,
      clipBehavior: Clip.hardEdge,
      decoration: const BoxDecoration(
        //设置四周圆角 角度
        borderRadius: BorderRadius.all(Radius.circular(43.25)),
      ),
      child: (controller.baseInfo?.avatarUrl == null)
          ? Image.asset(
              Assets.mineMineLogo,
              fit: BoxFit.fill,
            )
          : ClipOval(
              child: FadeInImage.assetNetwork(
                placeholder: Assets.mineMinePerson,
                image: controller.baseInfo?.avatarUrl ?? '',
                fit: BoxFit.cover,
              ),
            ),
    );
  }

  Container _buildChoosePhotoView() {
    return Container(
      decoration: BoxDecoration(
        //设置四周圆角 角度
        borderRadius: const BorderRadius.all(Radius.circular(10.75)),
        color: '#343331'.toColor(),
      ),
      child: InkWell(
        onTap: () {
          debugPrint('点击了头像');
          _showChoosePhotoView();
        },
        child: Container(
          margin:
              const EdgeInsets.only(left: 5.5, top: 6, right: 5.5, bottom: 5.5),
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage(Assets.mineChooseCamera),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildRowCell({
    required String title,
    String? text,
    void Function()? onTap,
  }) {
    String name = text ?? '';
    return SizedBox(
      height: 47,
      child: InkWell(
        onTap: onTap,
        child: Column(
          children: [
            Expanded(
              child: Row(
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    margin: const EdgeInsets.only(left: 14),
                    width: 100,
                    child: Text(
                      title,
                      style: TextStyle(
                        color: '#444444'.toColor(),
                        fontSize: 14,
                      ),
                    ),
                  ),
                  Expanded(
                    child: Text(
                      name.length > 8 ? '${name.substring(0, 8)}...' : name,
                      textAlign: TextAlign.right,
                      maxLines: 1,
                      style: TextStyle(
                        color: '#444444'.toColor(),
                        fontSize: 14,
                      ),
                    ),
                  ),
                  onTap == null
                      ? _rowPadding(33)
                      : Container(
                          margin: const EdgeInsets.only(
                            left: 10.5,
                            right: 15.5,
                          ),
                          width: 7,
                          height: 12,
                          child: Image.asset(
                            Assets.mineMineNext,
                            width: 7,
                          ),
                        ),
                ],
              ),
            ),
            _buildBottomLine(),
          ],
        ),
      ),
    );
  }

  double paddingSizeTop(BuildContext context) {
    return MediaQuery.of(context).padding.bottom;
  }

  void _showChoosePhotoView() async {
    // showModalBottomSheet(
    //     context: context,
    //     builder: (BuildContext context) {
    //       return SizedBox(
    //         height: 160 + paddingSizeTop(context),
    //         child: Column(
    //           children: [
    //             TextButton(
    //               onPressed: () {
    //                 Navigator.pop(context, null);
    //                 selectCamera();
    //               },
    //               child: const Text(
    //                 '拍摄',
    //                 style: TextStyle(color: Colors.black, fontSize: 14),
    //               ),
    //             ),
    //             Container(
    //               height: 0.5,
    //               color: '#E5E5E5'.toColor(),
    //             ),
    //             TextButton(
    //               onPressed: () {
    //                 debugPrint('点击了选择相册');
    //                 Navigator.pop(context, null);
    //                 selectImage();
    //               },
    //               child: const Text(
    //                 '从本地图库中选择',
    //                 style: TextStyle(color: Colors.black, fontSize: 14),
    //               ),
    //             ),
    //             Container(
    //               height: 5,
    //               color: '#E5E5E5'.toColor(),
    //             ),
    //             TextButton(
    //               onPressed: () => Navigator.pop(context, null),
    //               child: const Text(
    //                 '取消',
    //                 style: TextStyle(color: Colors.black, fontSize: 14),
    //               ),
    //             ),
    //           ],
    //         ),
    //       );
    //     });
  }

  selectImage() async {
    // XFile? image = await _imagePicker.pickImage(
    //   source: ImageSource.gallery,
    //   maxHeight: 120,
    //   maxWidth: 120,
    // );
    // if (image != null) {
    //   debugPrint('------1-----$image');
    //   this.image = image;
    //   setState(() {
    //     photoPath = image.path;
    //     debugPrint('photoPath==$photoPath'); //上传图片
    //     _uploadPhoto();
    //   });
    // }
  }

  selectCamera() async {
    // XFile? photo = await _imagePicker.pickImage(
    //   source: ImageSource.camera,
    //   preferredCameraDevice: CameraDevice.rear,
    //   maxHeight: 120,
    //   maxWidth: 120,
    // );
    // if (photo != null) {
    //   image = photo;
    //   setState(() {
    //     photoPath = photo.path;
    //     debugPrint('photoPath==$photoPath');
    //     //上传图片
    //     _uploadPhoto();
    //   });
    // }
  }

  _uploadPhoto() async {
    // FormData formData =
    //     FormData.fromMap({'file': await MultipartFile.fromFile(photoPath)});

    // ApiCallResult result = await APICaller.call(
    //   ERDSApiPath.uploadPhoto,
    //   data: formData,
    //   method: DioMethod.post,
    //   dataFormatFun: (json) {
    //     debugPrint('uploadjson==$json  avatarUrl==${json['avatarUrl']}');
    //     setState(() {
    //       widget.myMessage.avatarUrl = json['avatarUrl'];
    //     });
    //   },
    // );

    // if (result.success) {
    //   EasyLoading.dismiss();
    //   EasyLoading.showSuccess('头像上传成功！');
    //   _delayRefreshMineViewData();
    // } else {
    //   EasyLoading.dismiss();
    //   EasyLoading.showError(result.errorInfo);
    // }
  }

  void _pickAction() {
    // FocusManager.instance.primaryFocus?.unfocus();
    // List<String> data = [];
    // List<Region> temp =
    //     _areaList.where((element) => (element.name ?? '').isNotEmpty).toList();
    // Region? selected = lastRegion;

    // data = temp.map((e) => e.name ?? '').toList();
    // if (data.isEmpty) {
    //   return;
    // }

    // Pickers.showSinglePicker(context,
    //     data: data, selectData: selected.name ?? '', onConfirm: (data, idx) {
    //   setState(() {
    //     lastRegion = _areaList[idx];
    //   });
    //   _changeAreaRequest();
    // });
  }

  _delayRefreshMineViewData() {
    // Future.delayed(const Duration(seconds: 2), () {
    //   widget.callback();
    // });
  }

  Widget _buildBottomLine() {
    return Container(
      margin: const EdgeInsets.only(left: 15, right: 15),
      height: 1,
      decoration: BoxDecoration(
        color: '#E6EBF5'.toColor(),
      ),
    );
  }

  Container _rowPadding(double padding) {
    return Container(
      width: padding,
    );
  }
}
